﻿using Panuon.WPF;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive.Concurrency;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace MCPlatform.Components
{
    public class ActivationManager: NotifyPropertyChangedBase
    {
        string outputFile = "activate.enc"; // 输出文件的路径

        // 指定密钥和 IV
        byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");
        byte[] iv = Encoding.UTF8.GetBytes("0123456789abcdef");

       // private const string ActivationFilePath = "activation.txt"; // 保存激活信息的文件名

        public bool IsActivated { get; private set; } // 是否已激活

        public bool IsForver { get; private set; } // 是否永久

        public bool IsTrail { get;  set; } // 是否试用

        public bool IsOneYearTrial { get; set; } // 一年试用
        public DateTime ActivationDate { get; private set; } // 激活日期

        public DateTime ExpirationDate { get; private set; } // 到期日期

         DispatcherTimer timer = new DispatcherTimer();

        /// <summary>
        /// 产品名称
        /// </summary>
        public string ExpirationString
        {
            get => expirationString;
            set
            {
                Set(ref expirationString, value);

            }
        }

        private string expirationString = string.Empty;


        private  Stopwatch stopwatch = new Stopwatch();

        // public DateTime ExpirationDate { get; private set; } // 到期日期

        //单例模式
        private static ActivationManager? instance;

        private ActivationManager() 
        {
            timer.Interval = TimeSpan.FromSeconds(60);
            timer.Tick += Timer_Tick; ; ;
            
        }

        public static ActivationManager GetInstance()
        {
            if (instance == null)
            {
                instance = new ActivationManager();
            }

           

            return instance;
        }

        private  void Timer_Tick(object? sender, EventArgs e)
        {
            //运行过程中，每天检查一次剩余时间。如果软件重启就默认检查
            if (stopwatch.Elapsed > TimeSpan.FromDays(1))
            {
                stopwatch.Restart();
                CheckActivationStatus();
            }

            //激活时间过期，直接关闭使用
            if ((DateTime.Now > ExpirationDate) || (!IsActivated))
            {
                Application.Current?.Shutdown();
            }
        }





        // 激活函数，可以激活试用、激活永久
        // 如果成功激活，则返回true，否则返回false
        public int Activate(string actibatedCode)
        {
           bool Ret = LoadActivationInfo();
            if (IsForver)
            { // 已经激活过了，不能再次激活
                return 999;
            }

            if (actibatedCode.Equals("forever-FV"))
            { // 永久激活
                IsActivated = true;
                IsForver = true;
                ActivationDate = DateTime.Now;
                ExpirationDate = DateTime.MaxValue;
                ExpirationString = "有效期剩余：永久";
            }
            else if (actibatedCode.Equals("7Dtrial")  && !IsOneYearTrial)
            { // 试用激活
                IsActivated = true;
                IsTrail = true;
                ActivationDate = DateTime.Now;
                ExpirationDate = DateTime.Now.AddDays(30); // 7天试用期
            }
            else if (actibatedCode.Equals("trial") && (!IsTrail) && !IsOneYearTrial)
            { // 试用激活
                IsActivated = true;
                IsTrail = true;
                ActivationDate = DateTime.Now;
                ExpirationDate = DateTime.Now.AddDays(30); // 30天试用期
            }
            else if (actibatedCode.Equals("oneyear-1Y") && !IsOneYearTrial)
            { // 试用激活
                IsActivated = true;
                IsOneYearTrial = true;
                ActivationDate = DateTime.Now;
                ExpirationDate = DateTime.Now.AddYears(1); // 1年试用期
            }
            else
            {
                return -1;
            }

            if (IsActivated)
            {
                timer.Start();
                stopwatch.Start();
            }

            // 保存激活信息
            SaveActivationInfo();

            return 1;
        }

        // 检查是否已经激活，并计算剩余天数
        // 如果已经激活，则返回剩余天数，否则返回-1
        public int CheckActivationStatus()
        {
            bool Ret = LoadActivationInfo();
            if ((!Ret))
            {
                ExpirationString = "未激活";
                IsActivated = false;
                return -999;
            }

            if ((!IsActivated) )
            {
                ExpirationString = "未激活";              
                return -1;
            }
            if (IsForver)
            {
                IsForver = true;
                ExpirationString = "有效期剩余：永久";
                return -999;
            }
            TimeSpan remainingTime = ExpirationDate - DateTime.Now;
            if (remainingTime.TotalDays < 0)
            { // 已经过期了
                IsActivated = false;
                ActivationDate = DateTime.MinValue;
                ExpirationDate = DateTime.MinValue;
                ExpirationString = "激活已过期";
                SaveActivationInfo(); // 清除激活信息
                return -1;
            }
            else
            {
                ExpirationString = $"有效期剩余：{(int)remainingTime.TotalDays}天";
                return (int)remainingTime.TotalDays;
            }
        }

        // 保存激活信息到文件
        private void SaveActivationInfo()
        {
            StringBuilder plaintext = new StringBuilder();
            plaintext.AppendLine(IsActivated.ToString());
            plaintext.AppendLine(IsTrail.ToString());
            plaintext.AppendLine(IsOneYearTrial.ToString());
            plaintext.AppendLine(IsForver.ToString());
            plaintext.AppendLine(ActivationDate.ToString());
            plaintext.Append(ExpirationDate.ToString());
            // 创建 Aes 实例
            using (Aes aes = Aes.Create())
            {
                // 指定加密模式和填充模式
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.Key = key;
                aes.IV = iv;

                // 创建加密流
                ICryptoTransform encryptor = aes.CreateEncryptor();
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

                // 将明文数据写入加密流
                byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext.ToString());
                cryptoStream.Write(plaintextBytes, 0, plaintextBytes.Length);
                cryptoStream.FlushFinalBlock();

                // 将加密流中的数据写入 .enc 文件           
                byte[] encryptedBytes = memoryStream.ToArray();
                File.WriteAllBytes(outputFile, encryptedBytes);
            }
           
        }

        // 从文件中加载激活信息
        private bool LoadActivationInfo()
        {
            if (File.Exists(outputFile))
            {
                byte[] encryptedBytes = File.ReadAllBytes(outputFile);
                //创建 Aes 实例
                using (Aes aes = Aes.Create())
                {
                    // 指定加密模式和填充模式
                    aes.Mode = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;
                    aes.Key = key;
                    aes.IV = iv;

                    // 创建解密流
                    ICryptoTransform decryptor = aes.CreateDecryptor();
                    MemoryStream memoryStream = new MemoryStream(encryptedBytes);
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                    // 读取解密流中的数据
                    byte[] buffer = new byte[1024];
                    int readBytes = cryptoStream.Read(buffer, 0, buffer.Length);
                    StringBuilder sb = new StringBuilder();
                    while (readBytes > 0)
                    {
                        sb.Append(Encoding.UTF8.GetString(buffer, 0, readBytes));
                        readBytes = cryptoStream.Read(buffer, 0, buffer.Length);
                    }

                    // 解密得到的字符串
                    string decryptedText = sb.ToString();
                    var str = decryptedText.Split("\r\n");
                    if (str != null)
                    {
                        foreach (var item in str)
                        {

                            Console.WriteLine($"解密得到的字符串：{item}");
                        }
                        if (str.Length >= 5)
                        {
                            IsActivated = bool.Parse(str[0]);
                            IsTrail = bool.Parse(str[1]);
                            IsOneYearTrial = bool.Parse(str[2]);
                            IsForver = bool.Parse(str[3]);
                            ActivationDate = DateTime.Parse(str[4]);
                            ExpirationDate = DateTime.Parse(str[5]);
                        }

                    }

                }

                TimeSpan remainingTime = ExpirationDate - DateTime.Now;
                if (remainingTime.TotalDays > 0)
                {
                    timer.Start();
                    stopwatch.Start();

                }
               

                return true;
            }
            return false;
        }
    }
}
